package org.bluweb.g4wicket.language.translation;

import java.util.HashMap;
import java.util.Map;

import org.apache.wicket.Component;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.form.AbstractTextComponent;
import org.bluweb.g4wicket.G4WicketBehaviour;
import org.bluweb.g4wicket.G4WicketEvent;

@SuppressWarnings("serial")
public class Translation extends G4WicketBehaviour {

	private String sourceId;
	private String targetId;
	private boolean sourceIsTextComponent;
	private boolean targetIsTextComponent;

	@Override
	public void renderHead(IHeaderResponse response) {
		super.renderHead( response );
		
		Map<String,Object> parameters = new HashMap<String,Object>();
		parameters.put( "sourceId", this.sourceId );
		parameters.put( "targetId", this.targetId );		
		parameters.put( "sourceMethod", sourceIsTextComponent ? "value" : "innerHTML" );
		parameters.put( "targetMethod", targetIsTextComponent ? "value" : "innerHTML" );
		
		response.renderJavascript( this.getJavaScript( "Translation.js", parameters ), this.getId() );
	}	
	
	public void translate( G4WicketEvent event ) {
		
		this.execute( "translate" + this.getId() + "();", event );
	}

	@Override
	public void bind( Component component ) {
		component.setOutputMarkupId( true );
		this.sourceId = component.getMarkupId();
		this.targetId = component.getMarkupId();
		this.sourceIsTextComponent = component instanceof AbstractTextComponent;
		this.targetIsTextComponent = this.sourceIsTextComponent;
	}
	
	public void setTargetComponent( Component component ) {
		component.setOutputMarkupId( true );
		this.targetId = component.getMarkupId();
		this.targetIsTextComponent = component instanceof AbstractTextComponent;
	}
}
